<template>
  <view>
    <view class="modify-status">{{ isNewRecord ? 'N' : 'M' }}</view>
    <FormRender ref="FRD"></FormRender>
    <view class="floot-btn">
      <u-button @click="submit" :customStyle="cStyle" type="primary" text="保存提交" shape="circle"></u-button>
    </view>
  </view>
</template>
<script>
const { v4: uuidv4 } = require('uuid')

export default {
  name: 'ShowForm',
  data() {
    return {
      cStyle: {
        width: '80%',
      },
      formid: '',
      isNewRecord: true,
      recordId: '',
    }
  },
  onLoad(opt) {
    // console.log('showform opt', opt)
    this.formid = opt.id
  },
  mounted() {
    this.getData()
  },
  methods: {
    async submit() {
      const resData = await this.$refs.FRD.getData()
      if (!resData) return

      const resCheckSms = this.$refs.FRD.checkSms()
      if (!resCheckSms) return

      const resConfirm = await this.$confirm('确认保存本次填写的内容吗？')
      if (!resConfirm) return

      console.log('submit after getData ', resData)
      if (this.isNewRecord) {
        const openid = this.$store.state.vx_openid
        const script = `insert into formdata ([id],[formId],[openid],[dataobj]) values ('${uuidv4()}','${this.formid}','${openid}','${JSON.stringify(resData)}');`
        const r = await uni.$u.http.post(`/weixinNotify/AutoForm/AddItem`, { script })
        this.$alert(r)
      } else {
        const script = `update formdata set dataobj = '${JSON.stringify(resData)}' where id='${this.recordId}'`
        const r = await uni.$u.http.post(`/weixinNotify/AutoForm/AddItem`, { script })
        this.$alert(r)
      }
    },

    async getData() {
      let script = `select * from formlist where id ='${this.formid}'`
      const resSchema = await uni.$u.http.post(`/weixinNotify/AutoForm/GetFormList`, { script })
      const schema = JSON.parse(resSchema[0].schema)

      const openid = this.$store.state.vx_openid
      script = `select * from formdata where formId ='${this.formid}' and openid='${openid}'`
      const resModel = await uni.$u.http.post(`/weixinNotify/AutoForm/GetFormData`, { script })
      let initData = null
      if (resModel.length > 0) {
        const { id, dataobj } = resModel[0]
        initData = JSON.parse(dataobj)
        this.isNewRecord = false
        this.recordId = id
        // console.log('showform getData', initData)
      }
      this.$refs.FRD.load({ schema, initData })
    },
  },
}
</script>
<style>
.floot-btn {
  position: fixed;
  bottom: 25px;
  left: 0;
  width: 100%;
}
.modify-status {
  position: fixed;
  top: 6px;
  font-size: 12px;
  right: 6px;
  z-index: 99999;
  border-radius: 18px;
  width: 21px;
  height: 21px;
  line-height: 21px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
  color: #eee;
}
</style>
